var express = require("express");
const { UserModel } = require("../mongo/model");
var { aesEncrypt } = require("../utils/crypto");
var router = express.Router();

/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});
// 表单提交是post方法
router.all("/register", (req, res) => {
  var body = req.body;
  console.log(body);
  UserModel.findOne({
    $or: [{ username: body.username }, { phone: body.phone }],
  })
    .then((result) => {
      if (result) {
        res.send(
          `<script>alert('当前用户已经被注册，请重新再试');location.href='/register'</script>`
        );
      } else {
        UserModel.insertMany(body).then((data) => {
          res.send(
            `<script>alert('注册成功');location.href='/login?username=${aesEncrypt(
              body.username
            )}'</script>`
          );
        });
      }
    })
    .catch((err) => {
      res.send(
        `<script>alert('服务器异常，请重新再试');location.href='/register'</script>`
      );
    });
});
router.get("/login", (req, res) => {
  var query = req.query;
  var body = req.body;
  console.log(query);

  UserModel.findOne(query)
    .then((result) => {
      if (result) {
        req.session.username = query.username;
        req.session.phone = query.phone;
        res.redirect("/");
        // res.send(`<script>alert('登陆成功');location.href='/'</script>`);
      } else {
        res.send(
          `<script>alert('登陆失败，请重新再试');location.href='/login'</script>`
        );
      }
    })
    .catch((err) => {
      res.send(
        `<script>alert('服务器异常，请重新再试。${err}');location.href='/login'</script>`
      );
    });
});

router.get("/home", function (req, res, next) {
  res.send("首页");
});
router.get("/mine", function (req, res, next) {
  res.send("我的");
});

module.exports = router;
